package com.ruoyi.accountant.service.impl;

import com.ruoyi.accountant.domain.User;
import com.ruoyi.accountant.domain.UserExample;
import com.ruoyi.accountant.mapper.UserMapper;
import com.ruoyi.accountant.service.UserService;
import com.ruoyi.web.web.form.UserListForm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.sql.Timestamp;
import java.util.List;

@Service
@Transactional
public class UserServiceImpl implements UserService {
    //@Autowired
//    private UserDao userDao;

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> findAllBy(UserListForm userListForm) {
        return   userMapper.selectByExample(null);
    }

    @Override
    public void save(User user) {
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        user.setCreatetime(timestamp);
        user.setModifytime(timestamp);
        userMapper.insert(user);
    }

    @Override
    public void update(User u) {
        userMapper.updateByPrimaryKeySelective(u);
    }

    @Override
    public User findByUid(Long uid) {
        return userMapper.selectByPrimaryKey(uid);
    }

    @Override
    public void deleteAll(List<Long> uids) {
        for (Long uid : uids) {
            userMapper.deleteByPrimaryKey(uid);
        }
    }

    @Override
    public User findByLoginNameAndUpass(String loginName, String upass) {
        return userMapper.findByLoginNameAndUpass(loginName,upass);
    }

    @Override
    public User findByApiKey(String apiKey) {
        if(StringUtils.isEmpty(apiKey)) {
            return null;
        } else {
            UserExample userExample = new UserExample();
            userExample.createCriteria().andApiKeyEqualTo(apiKey);
            return (User) userMapper.selectByExample(userExample);
        }
    }
}
